from datetime import datetime

from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import MDFlatButton, MDRectangleFlatButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.gridlayout import MDGridLayout
from kivymd.uix.label import MDLabel
from kivymd.uix.pickers import MDDatePicker
from kivymd.uix.scrollview import ScrollView
from kivymd.uix.tab import MDTabs
from kivymd.uix.tab import MDTabsBase
from kivymd.uix.textfield import MDTextField
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.button import MDRectangleFlatIconButton

import controller
from Tests import *
from Views import *
from controller import ControllerDB


class Tab(MDBoxLayout, MDTabsBase):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class MainApp(MDApp):
    dialog = None

    data_tables = None
    d2 = None
    d3 = None
    d4 = None
    d5 = None
    ids = dict()
    controller = ControllerDB("postgresql://postgres:postgres@localhost:5432/journal")

    entries = []
    students = []
    cabinets = []
    laborants = []
    directions = []

    menu = None

    b1 = None
    b2 = None

    def __init__(self):
        super().__init__()

    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        tabs = MDTabs()

        self.data_tables = EntriesViews(self.entries).view()
        self.data_tables.bind(on_row_press=self.show_entry)
        b1 = MDBoxLayout(orientation="horizontal", size_hint=[1, 0.076], padding=dp(0.5), spacing=dp(10))
        self.b1 = b1
        sc1 = ScrollView()
        sc1.add_widget(self.data_tables)
        t1 = Tab(title="Записи", orientation="vertical")

        b1.add_widget(MDFlatButton(text="Добавить",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.add_entry))

        b1.add_widget(MDFlatButton(text="Фильтр_Каб",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.select_cabinet))

        b1.add_widget(MDFlatButton(text="Фильтр_Студ",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.select_student))

        b1.add_widget(MDFlatButton(text="Фильтр_Лаб",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=lambda m: self.select_laborant(m, 'bottom')))

        b1.add_widget(MDFlatButton(text="Фильтр_Комп",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.select_comp))

        b1.add_widget(MDRectangleFlatIconButton(icon="magnify",
                                                theme_icon_color="Custom",
                                                icon_color="orange",
                                                line_color="orange",
                                                text="Поиск",
                                                text_color="orange",
                                                font_size=dp(15),
                                                on_release=self.filter_entry))

        t1.add_widget(b1)
        t1.add_widget(sc1)

        t2 = Tab(title="Студенты", orientation="vertical")
        self.d2 = StudentsViews(self.students).view()
        self.d2.bind(on_row_press=self.show_student)
        b2 = MDBoxLayout(orientation="horizontal", size_hint=[1, 0.076], padding=dp(2), spacing=dp(10))
        self.b2 = b2

        b2.add_widget(MDFlatButton(text="Добавить",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.add_student))

        b2.add_widget(MDFlatButton(text="Фильтр_Напр",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.select_direction))

        b2.add_widget(MDRectangleFlatIconButton(icon="magnify",
                                                theme_icon_color="Custom",
                                                icon_color="orange",
                                                line_color="orange",
                                                text="Поиск",
                                                text_color="orange",
                                                font_size=dp(15),
                                                on_release=self.filter_student))

        sc2 = ScrollView()
        sc2.add_widget(self.d2)
        t2.add_widget(b2)
        t2.add_widget(sc2)

        t3 = Tab(title="Кабинеты", orientation="vertical")
        self.d3 = CabinetsViews(self.cabinets).view()
        self.d3.bind(on_row_press=self.show_cabinet)
        b3 = MDBoxLayout(orientation="horizontal", size_hint=[1, 0.076], padding=dp(2), spacing=dp(10))

        b3.add_widget(MDFlatButton(text="Добавить",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.add_cabinet))

        t3.add_widget(b3)

        sc3 = ScrollView()
        sc3.add_widget(self.d3)
        t3.add_widget(sc3)

        t4 = Tab(title="Лаборанты", orientation="vertical")
        self.d4 = LaborantsViews(self.laborants).view()
        self.d4.bind(on_row_press=self.show_laborant)
        b4 = MDBoxLayout(orientation="horizontal", size_hint=[1, 0.076], padding=dp(2), spacing=dp(10))

        b4.add_widget(MDFlatButton(text="Добавить",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.add_laborant))

        sc4 = ScrollView()
        sc4.add_widget(self.d4)
        t4.add_widget(b4)
        t4.add_widget(sc4)

        t5 = Tab(title="Направления", orientation="vertical")
        self.d5 = DirectionsViews(self.directions).view()
        self.d5.bind(on_row_press=self.show_direction)
        b5 = MDBoxLayout(orientation="horizontal", size_hint=[1, 0.076], padding=dp(2), spacing=dp(10))

        b5.add_widget(MDFlatButton(text="Добавить",
                                   theme_text_color="Custom",
                                   text_color=self.theme_cls.primary_color,
                                   line_color="orange",
                                   on_release=self.add_direction))

        sc5 = ScrollView()
        sc5.add_widget(self.d5)
        t5.add_widget(b5)
        t5.add_widget(sc5)

        tabs.add_widget(t1)
        tabs.add_widget(t2)
        tabs.add_widget(t3)
        tabs.add_widget(t4)
        tabs.add_widget(t5)

        self.update_data()

        return tabs

    def filter_student(self, instance):
        if self.b2.children[1].text == 'Фильтр_Напр':
            self.d2.row_data = [i.to_row() for i in self.students]
        else:
            f = self.b2.children[1].text
            self.d2.row_data = map(lambda m: m.to_row(), filter(lambda m: m.direction.name == f, self.students))

    def filter_entry(self, instance):
        ans = self.entries
        if self.b1.children[-2].text == 'Фильтр_Каб' and self.b1.children[-3].text == 'Фильтр_Студ' and self.b1.children[-4].text == 'Фильтр_Лаб' and self.b1.children[-5].text == 'Фильтр_Комп':
            self.data_tables.row_data = [i.to_row() for i in self.entries]
            return

        if self.b1.children[-2].text != 'Фильтр_Каб':
            f = self.b1.children[-2].text
            ans = filter(lambda m: m.cabinet.name == f, ans)
        if self.b1.children[-3].text != 'Фильтр_Студ':
            f = self.b1.children[-3].text
            ans = filter(lambda m: m.student.name == f, ans)
        if self.b1.children[-4].text != 'Фильтр_Лаб':
            f = self.b1.children[-4].text
            ans = filter(lambda m: m.laborant.second_name == f, ans)
        if self.b1.children[-5].text != 'Фильтр_Комп':
            f = self.b1.children[-5].text
            ans = filter(lambda m: str(m.comp_num) == f, ans)

        self.data_tables.row_data = map(lambda m: m.to_row(), ans)

    def update_data(self):
        self.entries = self.controller.get_all_entries()
        self.cabinets = self.controller.get_all_cabinets()
        self.directions = self.controller.get_all_directions()
        self.students = self.controller.get_all_students()
        self.laborants = self.controller.get_all_laborants()
        self.data_tables.row_data = [i.to_row() for i in self.entries]
        self.d2.row_data = [i.to_row() for i in self.students]
        self.d3.row_data = [i.to_row() for i in self.cabinets]
        self.d4.row_data = [i.to_row() for i in self.laborants]
        self.d5.row_data = [i.to_row() for i in self.directions]

    def select_cabinet(self, instance):
        self.menu = MDDropdownMenu()
        menu_items = [
            {
                "text": i.name,
                "on_release": lambda x=i.name: self.set_x(x, instance),
            } for i in self.cabinets]
        menu_items.insert(0, {"text": "-", "on_release": lambda x="-": self.set_x("Фильтр_Каб", instance)})
        self.menu.items = menu_items
        self.menu.caller = instance
        self.menu.position = "bottom"
        self.menu.open()

    def select_student(self, instance):
        self.menu = MDDropdownMenu()
        menu_items = [
            {
                "text": i.name,
                "on_release": lambda x=i.name: self.set_x(x, instance),
            } for i in self.students]
        menu_items.insert(0, {"text": "-", "on_release": lambda x="-": self.set_x("Фильтр_Студ", instance)})
        self.menu.items = menu_items
        self.menu.caller = instance
        self.menu.position = "bottom"
        self.menu.open()

    def select_direction(self, instance):
        self.menu = MDDropdownMenu()
        menu_items = [
            {
                "text": i.name,
                "on_release": lambda x=i.name: self.set_x(x, instance),
            } for i in self.directions]
        menu_items.insert(0, {"text": "-", "on_release": lambda x="-": self.set_x("Фильтр_Напр", instance)})
        self.menu.items = menu_items
        self.menu.caller = instance
        self.menu.position = "bottom"
        self.menu.open()

    def select_laborant(self, instance, pos):
        self.menu = MDDropdownMenu()
        menu_items = [
            {
                "text": i.second_name,
                "on_release": lambda x=i.second_name: self.set_x(x, instance),
            } for i in self.laborants]
        menu_items.insert(0, {"text": "-", "on_release": lambda x="-": self.set_x("Фильтр_Лаб", instance)})
        self.menu.items = menu_items
        self.menu.caller = instance
        self.menu.position = pos
        self.menu.open()

    def select_comp(self, instance):
        self.menu = MDDropdownMenu()
        menu_items = [
            {
                "text": str(i),
                "on_release": lambda x=str(i): self.set_x(x, instance),
            } for i in range(1, 16)]
        menu_items.insert(0, {"text": "-", "on_release": lambda x="-": self.set_x("Фильтр_Комп", instance)})
        self.menu.items = menu_items
        self.menu.caller = instance
        self.menu.position = "bottom"
        self.menu.open()

    def set_x(self, x, instance):
        instance.text = x
        self.menu.dismiss()

    def show_entry(self, instance_table, instance_row):
        self.dialog = None
        if not self.dialog:
            index = instance_row.index
            cols_num = len(instance_table.column_data)
            row_num = int(index / cols_num)

            s = self.data_tables.row_data[row_num]
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(

                    MDLabel(text="ID"),
                    MDLabel(
                        text=s[0],
                    ),
                    MDLabel(text="Номер пары"),
                    MDTextField(
                        text=s[1],
                    ),
                    MDLabel(text="Номер компьютера"),
                    MDTextField(
                        text=s[2],
                    ),
                    MDLabel(text="Фамилия студента"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        text=s[3],
                        on_release=self.select_student
                    ),
                    MDLabel(text="Дата"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        text=s[4],
                        on_release=self.show_date_picker
                    ),
                    MDLabel(text="Фамилия лаборанта"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        text=s[5],
                        on_release=lambda m: self.select_laborant(m, 'top')
                    ),
                    MDLabel(text="Название кабинета"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        text=s[6],
                        on_release=self.select_cabinet
                    ),
                    rows=7,
                    spacing="5dp",
                    size_hint_y=None,
                    height="500dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.save_entry,
                    ),
                    MDFlatButton(
                        text="Удалить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=lambda m: self.delete_entry(m, int(s[0])),
                    ),
                ],
            )
        self.dialog.open()

    def delete_entry(self, instance, id: int):
        self.controller.delete_entry(id)
        self.update_data()
        self.dialog.dismiss()

    def on_save(self, _instance, value, _date_range, button):
        button.text = str(value)

    def show_date_picker(self, instance):
        date1 = datetime.strptime(instance.text, "%Y-%m-%d").date()
        date_dialog = MDDatePicker(year=date1.year, month=date1.month, day=date1.day)
        date_dialog.bind(on_save=lambda ins, val, drange: self.on_save(ins, val, drange, instance))
        date_dialog.open()

    def close(self, instance):
        self.dialog.dismiss()

    def save_entry(self, instance):
        id = int(self.dialog.content_cls.children[-2].text)
        lesson_num = int(self.dialog.content_cls.children[-4].text)
        comp_num = int(self.dialog.content_cls.children[-6].text)
        student_name = self.dialog.content_cls.children[-8].text
        lesson_date = datetime.strptime(self.dialog.content_cls.children[-10].text, "%Y-%m-%d").date()
        laborant_name = self.dialog.content_cls.children[-12].text
        cabinet_name = self.dialog.content_cls.children[-14].text

        with self.controller.session() as s:
            laborant = s.query(controller.Laborant).filter_by(second_name=laborant_name).one()
            cabinet = s.query(controller.Cabinet).filter_by(name=cabinet_name).one()
            student = s.query(controller.Student).filter_by(name=student_name).one()
            entry = controller.Entry(id=id, cabinet_id=cabinet.id, student_id=student.id, laborant_id=laborant.id,
                                     comp_num=comp_num, lesson_num=lesson_num, lesson_date=lesson_date)
            s.merge(entry)
            s.commit()

        self.update_data()

        self.dialog.dismiss()

    def create_entry(self, instance):
        lesson_num = int(self.dialog.content_cls.children[-2].text)
        comp_num = int(self.dialog.content_cls.children[-4].text)
        student_name = self.dialog.content_cls.children[-6].text
        lesson_date = datetime.strptime(self.dialog.content_cls.children[-8].text, "%Y-%m-%d").date()
        laborant_name = self.dialog.content_cls.children[-10].text
        cabinet_name = self.dialog.content_cls.children[-12].text

        with self.controller.session() as s:
            laborant = s.query(controller.Laborant).filter_by(second_name=laborant_name).one().to_model()
            cabinet = s.query(controller.Cabinet).filter_by(name=cabinet_name).one().to_model()
            student = s.query(controller.Student).filter_by(name=student_name).one().to_model()
            entry = Entry(cabinet=cabinet, student=student, laborant=laborant,
                          comp_num=comp_num, lesson_num=lesson_num, lesson_date=lesson_date)
            self.controller.create_entry(entry)
            s.commit()

        self.update_data()

        self.dialog.dismiss()

    def add_entry(self, instance):
        self.dialog = None
        if not self.dialog:
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(
                    MDLabel(text="Номер пары"),
                    MDTextField(),
                    MDLabel(text="Номер компьютера"),
                    MDTextField(),
                    MDLabel(text="Фамилия студента"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        on_release=self.select_student
                    ),
                    MDLabel(text="Дата"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        text=str(date.today()),
                        on_release=self.show_date_picker
                    ),
                    MDLabel(text="Фамилия лаборанта"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        on_release=lambda m: self.select_laborant(m, 'top')
                    ),
                    MDLabel(text="Название кабинета"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        on_release=self.select_cabinet
                    ),
                    rows=7,
                    spacing="5dp",
                    size_hint_y=None,
                    height="500dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Отменить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Добавить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.create_entry,
                    ),
                ],
            )
        self.dialog.open()

    def add_to_db(self):
        lesson_num = self.dialog.content_cls.children[-2].text
        comp_num = self.dialog.content_cls.children[-4].text
        student_name = self.dialog.content_cls.children[-6].text
        lesson_date = self.dialog.content_cls.children[-8].text
        laborant_name = self.dialog.content_cls.children[-10].text
        cabinet_name = self.dialog.content_cls.children[-12].text

        self.dialog.dismiss()

    def show_student(self, instance_table, instance_row):
        self.dialog = None
        if not self.dialog:
            index = instance_row.index
            cols_num = len(instance_table.column_data)
            row_num = int(index / cols_num)

            s = self.d2.row_data[row_num]
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(

                    MDLabel(text="ID"),
                    MDLabel(
                        text=s[0],
                    ),
                    MDLabel(text="Фамилия студента"),
                    MDTextField(
                        text=s[1],
                    ),
                    MDLabel(text="Название направления"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        text=s[2],
                        on_release=self.select_direction
                    ),

                    rows=3,
                    spacing="5dp",
                    size_hint_y=None,
                    height="300dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.save_student,
                    ),
                    MDFlatButton(
                        text="Удалить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=lambda m: self.delete_student(m, int(s[0])),
                    ),
                ],
            )
        self.dialog.open()

    def delete_student(self, instance, id: int):
        self.controller.delete_student(id)
        self.update_data()
        self.dialog.dismiss()

    def close_student(self, instance):
        self.dialog.dismiss()

    def create_student(self, instance):
        name = self.dialog.content_cls.children[-2].text
        direction_name = self.dialog.content_cls.children[-4].text
        with self.controller.session() as s:
            direction = s.query(controller.Direction).filter_by(name=direction_name).one()
            student = Student(name=name, direction=direction.to_model())
            self.controller.create_student(student)
        self.update_data()
        self.dialog.dismiss()

    def add_student(self, instance):
        self.dialog = None
        if not self.dialog:
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(
                    MDLabel(text="Фамилия студента"),
                    MDTextField(),
                    MDLabel(text="Название направления"),
                    MDRectangleFlatButton(
                        line_color="orange",
                        on_release=self.select_direction
                    ),

                    rows=3,
                    spacing="5dp",
                    size_hint_y=None,
                    height="300dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.create_student,
                    ),
                ],
            )
        self.dialog.open()

    def save_student(self, instance):
        id = int(self.dialog.content_cls.children[-2].text)
        name = self.dialog.content_cls.children[-4].text
        direction_name = self.dialog.content_cls.children[-6].text

        with self.controller.session() as s:
            direction = s.query(controller.Direction).filter_by(name=direction_name).one()
            entry = controller.Student(id=id, name=name, direction_id=direction.id)
            s.merge(entry)
            s.commit()

        self.update_data()

        self.dialog.dismiss()

    def show_cabinet(self, instance_table, instance_row):
        self.dialog = None
        if not self.dialog:
            index = instance_row.index
            cols_num = len(instance_table.column_data)
            row_num = int(index / cols_num)

            s = self.d3.row_data[row_num]
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(

                    MDLabel(text="ID"),
                    MDLabel(
                        text=s[0],
                    ),
                    MDLabel(text="Название кабинета"),
                    MDTextField(
                        text=s[1],
                    ),

                    rows=2,
                    spacing="5dp",
                    size_hint_y=None,
                    height="200dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.save_cabinet,
                    ),
                    MDFlatButton(
                        text="Удалить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=lambda m: self.delete_cabinet(m, int(s[0])),
                    ),
                ],
            )
        self.dialog.open()

    def delete_cabinet(self, instance, id: int):
        self.controller.delete_cabinet(id)
        self.update_data()
        self.dialog.dismiss()

    def close_cabinet(self, instance):
        self.dialog.dismiss()

    def save_cabinet(self, instance):
        id = int(self.dialog.content_cls.children[-2].text)
        name = self.dialog.content_cls.children[-4].text

        with self.controller.session() as s:
            entry = controller.Cabinet(id=id, name=name)
            s.merge(entry)
            s.commit()

        self.update_data()

        self.dialog.dismiss()

    def create_cabinet(self, instance):
        name = self.dialog.content_cls.children[-2].text
        cabinet = Cabinet(name=name)
        self.controller.create_cabinet(cabinet)
        self.update_data()
        self.dialog.dismiss()

    def add_cabinet(self, instance_table):
        self.dialog = None
        if not self.dialog:
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(

                    MDLabel(text="Название кабинета"),
                    MDTextField(

                    ),

                    rows=2,
                    spacing="5dp",
                    size_hint_y=None,
                    height="200dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.create_cabinet,
                    )

                ],
            )
        self.dialog.open()

    def show_laborant(self, instance_table, instance_row):
        self.dialog = None
        if not self.dialog:
            index = instance_row.index
            cols_num = len(instance_table.column_data)
            row_num = int(index / cols_num)

            s = self.d4.row_data[row_num]
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(

                    MDLabel(text="ID"),
                    MDLabel(
                        text=s[0],
                    ),
                    MDLabel(text="Фамилия лаборанта"),
                    MDTextField(
                        text=s[1],
                    ),

                    rows=2,
                    spacing="5dp",
                    size_hint_y=None,
                    height="200dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.save_laborant,
                    ),
                    MDFlatButton(
                        text="Удалить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=lambda m: self.delete_laborant(m, int(s[0])),
                    ),
                ],
            )
        self.dialog.open()

    def delete_laborant(self, instance, id: int):
        self.controller.delete_laborant(id)
        self.update_data()
        self.dialog.dismiss()

    def close_laborant(self, instance):
        self.dialog.dismiss()

    def save_laborant(self, instance):
        id = int(self.dialog.content_cls.children[-2].text)
        second_name = self.dialog.content_cls.children[-4].text

        with self.controller.session() as s:
            entry = controller.Laborant(id=id, second_name=second_name)
            s.merge(entry)
            s.commit()

        self.update_data()

        self.dialog.dismiss()

    def create_laborant(self, instance):
        second_name = self.dialog.content_cls.children[-2].text
        laborant = Laborant(second_name=second_name)
        self.controller.create_laborant(laborant)
        self.update_data()
        self.dialog.dismiss()

    def add_laborant(self, instance):
        self.dialog = None
        if not self.dialog:
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(
                    MDLabel(text="Фамилия лаборанта"),
                    MDTextField(
                        text='',
                    ),

                    rows=2,
                    spacing="5dp",
                    size_hint_y=None,
                    height="200dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.create_laborant,
                    ),
                ],
            )
        self.dialog.open()

    def show_direction(self, instance_table, instance_row):
        self.dialog = None
        if not self.dialog:
            index = instance_row.index
            cols_num = len(instance_table.column_data)
            row_num = int(index / cols_num)

            s = self.d5.row_data[row_num]
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(

                    MDLabel(text="ID"),
                    MDLabel(
                        text=s[0],
                    ),
                    MDLabel(text="Название направления"),
                    MDTextField(
                        text=s[1],
                    ),

                    rows=2,
                    spacing="5dp",
                    size_hint_y=None,
                    height="200dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.save_direction,
                    ),
                    MDFlatButton(
                        text="Удалить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=lambda m: self.delete_direction(m, s[0]),
                    ),
                ],
            )
        self.dialog.open()

    def delete_direction(self, instance, id: int):
        self.controller.delete_direction(id)
        self.update_data()
        self.dialog.dismiss()

    def close_direction(self, instance):
        self.dialog.dismiss()

    def save_direction(self, instance):
        id = int(self.dialog.content_cls.children[-2].text)
        name = self.dialog.content_cls.children[-4].text

        with self.controller.session() as s:
            entry = controller.Direction(id=id, name=name)
            s.merge(entry)
            s.commit()

        self.update_data()

        self.dialog.dismiss()

    def create_direction(self, instance):
        name = self.dialog.content_cls.children[-2].text
        direction = Direction(name=name)
        self.controller.create_direction(direction)
        self.update_data()
        self.dialog.dismiss()

    def add_direction(self, instance):
        self.dialog = None
        if not self.dialog:
            self.dialog = MDDialog(
                title="Корректирование данных",
                type="custom",
                content_cls=MDGridLayout(
                    MDLabel(text="Название направления"),
                    MDTextField(),

                    rows=2,
                    spacing="5dp",
                    size_hint_y=None,
                    height="200dp",
                ),
                buttons=[
                    MDFlatButton(
                        text="Закрыть",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.close,
                    ),
                    MDFlatButton(
                        text="Сохранить",
                        theme_text_color="Custom",
                        text_color=self.theme_cls.primary_color,
                        on_release=self.create_direction,
                    ),
                ],
            )
        self.dialog.open()


MainApp().run()
